package org.mj.im.common.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;

import java.util.Date;

public class JwtUtils {
    public static String sign(Long userId,String info,long expireIn,String secret){
        try{
            Date date = new Date(System.currentTimeMillis()+expireIn*1000);
            Algorithm algorithm = Algorithm.HMAC256(secret);
            return JWT.create()
                    .withAudience(String.valueOf(userId))
                    .withClaim("info",info)
                    .withExpiresAt(date)
                    .withIssuer("im-server")
                    .sign(algorithm);
        }catch (Exception e){
            return null;
        }
    }

    public static Long getUserId(String token){
        try{
            return Long.valueOf(JWT.decode(token).getAudience().get(0));
        }catch (JWTDecodeException e){
            return null;
        }
    }

    public static String getInfo(String token){
        try{
            return JWT.decode(token).getClaim("info").asString();
        }catch (JWTDecodeException exception){
            return null;
        }
    }
    //TODO 可以改造成成功就返回info。失败就null
    public static boolean checkToken(String token,String secret){
        try{
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);
            return true;
        }catch (JWTVerificationException exception){
            return false;
        }
    }
    public static Boolean checkSign(String token,String secret) {
        try{
            Algorithm algorithm  = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);
            return true;
        }catch (JWTVerificationException e) {
            return false;
        }
    }
}
